﻿
@{
    Layout = "";
}
<style>
    .ngdialog.ngdialog-theme-plain .ngdialog-content {
        width: 60% !important;
    }

    .ngdialog-theme-custom {
      padding-bottom: 160px;
      padding-top: 120px;
    }

</style>
<div ng-controller="BedListController">
    <h3>公寓管理</h3>

    <div class="panel panel-default" ng-class="{ 'whirl standard': isLoading}">

        <div class="panel-heading">
            <div class="form-inline ng-pristine ng-valid">
                <div class="form-group">
                    <input id="input-email" placeholder="公寓号或者大楼号或者公寓号" class="form-control" type="text" ng-model="Keywords">                    
                    <button type="submit" class="btn btn-labeled btn-primary" ng-click="tableParams.$params.page = 1;tableParams.reload()" ng-model="Keywords">
                        <span class="btn-label">
                            <em class="fa fa-search"></em>
                        </span>搜索
                    </button>
                </div>
                <div class="form-group">
                    <button type="submit" class="btn btn-labeled btn-success" ng-click="BedAdd(0)" ng-show="UserInfo.IsAdd || UserInfo.IsAdmin">
                        <span class="btn-label">
                            <em class="fa fa-plus"></em>
                        </span>新增
                    </button>
                </div>
                <div class="form-group">
                    <button type="button" class="btn btn-labeled btn-success" ng-click="godt()">
                        <span class="btn-label">
                            <em class="fa fa-upload"></em>
                        </span>导出报表
                    </button>
                </div>
                <div class="form-group">
                    <button type="button" class="btn btn-labeled btn-success" ng-click="Import()">
                        <span class="btn-label">
                            <em class="fa fa-download"></em>
                        </span>数据导入
                    </button>
                </div>
            </div>
        </div>
        <div class="panel-body">
            <div class="table-responsive">
                <table ng-table="tableParams" class="table table-striped table-bproducted table-hover">
                    <tbody>
                        <tr ng-repeat="item in $data" ng-show="UserInfo.IsQuery || UserInfo.IsAdmin">
                            
                            <td data-title="'大楼号'" class="text-center">{{item.BuildingNO}}</td>                            
                            <td data-title="'公寓号'" class="text-center">{{item.RoomNO}}</span></td>
                            <td data-title="'公寓类型'" class="text-center">{{item.RoomTypeName}}</td>
                            <td data-title="'公寓性质'" class="text-center">{{item.RoomAttrName}}</td>
                            <td data-title="'床位编号'" class="text-center">{{item.BedNO}}</td>
                            <td data-title="'柜号'" class="text-center">{{item.CupboardNO}}</td>
                            <td data-title="'操作'" nowrap="nowrap" class="text-center">
                                @*<button type="button" ng-click="BuildingLocation(item.BuildingNO)" class="btn btn-sm btn-info" title="位置">
                                    <em class="fa fa-location-arrow"></em>
                                </button>*@
                                <button type="button" ng-click="BedEdit(item.Id)" class="btn btn-sm btn-edit" title="编辑" ng-show="UserInfo.IsEdit ||UserInfo.IsAdmin">
                                    <em class="fa fa-edit"></em>
                                </button>
                                <button type="button" ng-click="BedDel($index, item.Id)" class="btn btn-sm btn-danger" title="删除" ng-show="UserInfo.IsDel || UserInfo.IsAdmin">
                                    <em class="fa fa-trash"></em>
                                </button>
                               
                            </td>
                        </tr>
                    </tbody>
                </table>
            </div>
        </div>
        
    </div>   

</div>

<script type="text/ng-template" id="deleteConfirmDialog">
    <div class="ngdialog-message text-center">
        <h3>确定要删除吗?</h3>
        <button type="button" ng-click="confirm()" class="btn btn-primary mr">确认</button>
        <button type="button" ng-click="closeThisDialog('button')" class="btn btn-default">取消</button>
    </div>
</script>

<script type="text/ng-template" id="WarningImport">
    <div class="ngdialog-message text-center">
        <h3></h3>
        
    </div>
</script>


<script type="text/ng-template" id="ImportData">
    <div class="ngdialog-message">    
        <div class="row">
            <div class="col-md-12">                
                <h3 id="myModalLabel">床位导入</h3>
                <p>
                    导入说明： 	请先下载模板，仔细阅读表头文字说明。请严格按照表头说明填入内容，以确保导入顺利完成。
                </p>
                <div id="uploader" class="wu-example">
                    <div class="btns">
                        <a class="btn btn-primary" id="btnExportTemplete" href="Templete/Bed/床位导入模板.xlsx">模板下载</a>
                    </div>
                </div>

                <div class="modal-footer">
                    <!--用来存放文件信息-->
                    <div id="thelist" class="text-left" uploader="uploader"></div>
                    
                    <input id="fileInput" type="file" nv-file-select="" style="display: none;" accept=".csv, application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/vnd.ms-excel" uploader="uploader" />

                    <button id="picker" class="btn btn-default" ng-click="selectfile()">选择文件</button>
                        
                    <button id="ctlBtn" class="btn btn-primary" ng-click="Uploadfile()">开始上传</button>
                    <button type="button" ng-click="closeThisDialog('button')" class="btn btn-default">取消</button>
                </div>
            </div>
        </div>
    </div>
</script>

<script>
    App.controller('BedListController', [
    '$scope', '$resource', '$state', '$route', 'ngDialog', '$http', 'ngTableParams', 'ngTableDataService', 'Notify', '$filter', "$stateParams", "$timeout", "toaster", "FileUploader",'$compile',
        function ($scope, $resource, $state, $route, ngDialog, $http, ngTableParams, ngTableDataService, Notify, $filter, $stateParams, $timeout, toaster, FileUploader, $compile) {
            'use strict';
            //楼层单元
            $scope.isLoading = true;
            $scope.uploading = false;
            $scope.fileUploadEndFlag = false;
            //数据查询
            $scope.tableParams = new ngTableParams({
                page: 1,
                count: 10,
                sorting: {
                    BuildingNO: 'asc',     // 初始化排序
                    RoomNO: 'asc'     // 
                }
            }, {
                getData: function ($defer, params) {
                    $scope.isLoading = true;
                    var requestParams = {
                        Skip: (params.page() - 1) * params.count(),
                        Take: params.count(),
                        Keywords: $scope.Keywords,
                        UnitLevel: $scope.UnitLevel
                    };

                    $http.post('/Bed/GetBedList', ngTableDataService.getServerSideParams(params.orderBy().toString(), params, requestParams))
                        .success(function (data, status) {
                            params.total(data.Total);
                            $defer.resolve(data.Results);
                            $scope.UserInfo = data._UserInfo;
                            $scope.isLoading = false;
                        });
                }
            });
            
            $scope.godt = function () {
               
                var keyword = "";
                if ($scope.Keywords != undefined)
                {
                    keyword = $scope.Keywords;
                }

                location.href = "/Report/GetMemberList?Keywords=" + keyword + "&UnitLevel=" + $scope.UnitLevel;
            }
                        
            //跳转新增页面
            $scope.BedAdd = function () {
                $state.go('app.beddetail', { "id": 0 });
            }

            
            //跳转编辑页面
            $scope.BedEdit = function (id) {
                $state.go('app.beddetail', { "id": id });
            }

            //删除大楼
            $scope.BedDel = function (index, id) {
                ngDialog.openConfirm({
                    template: 'deleteConfirmDialog',
                    className: 'ngdialog-theme-default'
                }).then(function (value) {
                    $scope.isLoading = true;
                    $http.post("/Bed/BedDel", { BuildingNO: id }).then(function (returnData) {
                        if (returnData.data.isSuccess) {
                            $scope.tableParams.data.splice(index, 1);
                            Notify.alert('操作成功!', { status: 'success' });
                        } else {
                            Notify.alert(returnData.data.msg, { status: 'warning' });
                        }
                        $scope.isLoading = false;
                    });
                }, function (reason) {
                }
                );
            };

            //导入数据
            $scope.Import = function () {
                ngDialog.openConfirm({
                    template: 'ImportData',
                    className: 'ngdialog-theme-plain',
                    scope: $scope,
                    
                }).then(function (value) {

                }, function (reason) {

                }
                );
            };
            
            //-------------上传文件选择相关
            $scope.selectfile = function () {
                $("#fileInput").click();
                $("#fileInput").on('change', function (e) {                    
                    //e.currentTarget.files 是一个数组，如果支持多个文件，则需要遍历
                    $scope.file = e.currentTarget.files[0];
                });
            };

            
            var handleFileSelect = function (evt) {
                var file = $scope.uploadSelectFile = evt.currentTarget.files[0];
                if (!evt.currentTarget.files[0] || !/\.(xls|xlsx)$/.test(evt.currentTarget.files[0].type)) {
                    Notify.alert('请选择excel文件', { status: 'warning' });
                    return false;
                }
                //if (file.size > 1 * 1024 * 1024) {
                //    Notify.alert('图片大小不能大于1MB', { status: 'warning', timeout: 3000 });
                //    $scope.uploadSelectFile = null;
                //    return false;
                //}
                var reader = new FileReader();
                reader.onload = function (evt) {
                    $scope.$apply(function ($scope) {
                        //$scope.myCroppedImage = evt.target.result;

                    });
                };
                if (file)
                    reader.readAsDataURL(file);
            };

            angular.element(document.querySelector('#fileInput')).on('change', handleFileSelect);
            var uploader = $scope.uploader = new FileUploader({
                url: '/Bed/UpLoadProcess',
                formdata: {
                    file: $scope.file
                },
                autoUpload:false
            });
            
            uploader.filters.push({
                name: 'customFilter',
                fn: function (item /*{File|FileLikeObject}*/, options) {
                    return this.queue.length < 10;
                }
            });
            


            // CALLBACKS
            uploader.onWhenAddingFileFailed = function (item /*{File|FileLikeObject}*/, filter, options) {
                console.info('onWhenAddingFileFailed', item, filter, options);
            };

            uploader.onAfterAddingFile = function (fileItem) {
                //debugger
                //if (/\.(xls|xlsx)$/.test(fileItem.file.name)) {
                //    document.getElementById('thelist').innerHTML = fileItem.file.name;
                //    $scope.fileItem = fileItem;
                    
                //}
                //else {
                //    Notify.alert('请选择excel文件', { status: 'warning' });
                //}
                console.info('onAfterAddingFile', fileItem);                
            };

            uploader.onAfterAddingAll = function (addedFileItems) {

                $scope.uploader.progress = 0;
                $("#thelist").empty();                
                for (var i = 0; i < addedFileItems.length; i++)
                {
                    if (/\.(xls|xlsx)$/.test(addedFileItems[i].file.name)) {
                        var filehtml = '<div id="file' + i.toString() + '" class="item">' + addedFileItems[i].file.name + '</div>';
                        var filetemplate = angular.element(filehtml);
                        var fileElement = $compile(filetemplate)($scope);
                        angular.element('#thelist').append(fileElement);
                                                
                        var html = '<div style="" class="progress progress-xs" ng-show="uploading">'+
                                    '<div role="progressbar" ng-style="{ \'width\': uploader.progress + \'% \' }" class="progress-bar"></div>'+
                                     '</div>';
                        var template = angular.element(html);
                        var mobileDialogElement = $compile(template)($scope);
                        angular.element('#thelist').append(mobileDialogElement);
                    }
                    else {
                        Notify.alert('请选择excel文件', { status: 'warning' });
                        break;
                    }
                }
                $("#thelist").append('<p class="state">请上传.....</p>');                

                $scope.addedFileItems = addedFileItems;
                console.info('onAfterAddingAll', addedFileItems);
            };

            uploader.onBeforeUploadItem = function (item) {
                console.info('onBeforeUploadItem', item);
            };

            uploader.onProgressItem = function (fileItem, progress) {
                console.info('onProgressItem', fileItem, progress);
            };

            uploader.onProgressAll = function (progress) {
                //  console.info('onProgressAll', progress);
            };

            uploader.onSuccessItem = function (fileItem, response, status, headers) {
                $("#fileInput").val("");
                $scope.uploader.progress = 0;
                $scope.fileUploadEndFlag = true;
                if (response.result == true)
                {
                    
                }
                else
                {
                    //for(var i = 0; i< response.errorstr.length; i++)
                    //{
                        
                    //    var html = '<div id="error' + i.toString() + '" class="label label-danger">' + response.errorstr[i] + '</div>';
                    //    var template = angular.element(html);
                    //    var Element = $compile(template)($scope);
                    //    angular.element('#thelist').append(Element);
                    //}
                    
                    Notify.alert(response.error, { status: 'warning' });

                    //ngDialog.open({
                    //    template: '<div class="modal-header"><h4 class="modal-title">'+response.error+'</h4></div>' +
                    //                '<div class="modal-footer"><button type="submit" class="btn" ng-click="confirmImport()" >确定</button>' +
                    //                '</div>',
                    //    className: 'ngdialog-theme-plain',
                    //    plain: true,
                    //    overlay: false,
                    //    appendClassName: 'ngdialog-custom',
                    //    controller: function ($scope) {  
                    //        $scope.confirmImport = function () {
                    //            $scope.closeThisDialog();
                    //        };

                    //    }  
                    //});

                    //$scope.errorImport = response
                }
                console.info('onSuccessItem', fileItem, response, status, headers);
            };

            uploader.onErrorItem = function (fileItem, response, status, headers) {
                Notify.alert("文件导入失败！", { status: 'warning' });
                console.info('onErrorItem', fileItem, response, status, headers);
            };

            uploader.onCancelItem = function (fileItem, response, status, headers) {
                console.info('onCancelItem', fileItem, response, status, headers);
            };

            uploader.onCompleteItem = function (fileItem, response, status, headers) {
                console.info('onCompleteItem', fileItem, response, status, headers);
            };

            uploader.onCompleteAll = function () {
                $scope.uploading = false;
            };
            
            //上传文件
            $scope.Uploadfile = function () {
                for (var i = 0; i < $scope.addedFileItems.length; i++)
                {
                    if (/\.(xls|xlsx)$/.test(document.getElementById('file'+i.toString()).innerHTML)) {
                        $scope.uploading = true;
                        $scope.addedFileItems[i].upload();
                    }
                }
            };
             
        }]);
</script>
